﻿using Dm.filter.log;
using Newtonsoft.Json;
using PhysicalExamination5.Interface;
using PhysicalExamination5.Model;
using PhysicalExamination5.Model.DataMaintenance;
using PhysicalExamination5.Model.PhysicalExamination;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace PhysicalExamination5.Service
{
    public class SLogin : ILogin
    {
        private readonly ISqlSugarClient db;
        public SLogin(ISqlSugarClient db)
        {
            this.db = db;
        }
        public string Initialize(string stripaddress)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】");

                string databaseName = ((Microsoft.Data.SqlClient.SqlConnection)db.Ado.Connection).Database;
                string serverIpAddress = ((Microsoft.Data.SqlClient.SqlConnection)db.Ado.Connection).DataSource;
                string strGongSiMingCheng = new SqlSugarRepository<HeXinXinXi>(db).getByWhere(t => t.BiaoShi == "公司名称").Select(t => t.CanShuZhi).FirstOrDefault();
                var ShouQuan = new SqlSugarRepository<MY_YiYuanShouQuan>(db).getAll().Select(t => new
                {
                    t.XiTongMingCheng,
                    t.YiYuanMingCheng
                }).Distinct()
                .ToList();
                string strYiYuanMingCheng = new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, ShouQuan[0].YiYuanMingCheng) == 0 ? strFanHuiZhi : "";
                List<string> listXiTongMingCheng = ShouQuan.Select(t => new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, t.XiTongMingCheng) == 0 ? strFanHuiZhi : "").ToList();
                if (listXiTongMingCheng.Count == 0)
                {
                    nret = -1;
                    strFanHuiZhi = "当前用户未授权请先进行授权操作";
                    goto PROC_EXIT;
                }


            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = new
                    {
                        strGongSiMingCheng,
                        strYiYuanMingCheng,
                        listXiTongMingCheng,
                        stripaddress,
                        serverIpAddress,
                        databaseName
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 根据用户ID返回用户名和院区权限
        /// </summary>
        /// <param name="strUserId"></param>
        /// <returns></returns>
        public string SelUserDate(string strUserId)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:接收参数【{strUserId}】");

                #region 声明变量

                string strUserName = "";
                List<string> list院区 = new List<string>();

                #endregion

                #region 验证数据

                if (string.IsNullOrEmpty(strUserId))
                {
                    nret = 1;
                    strFanHuiZhi = "用户Id为空！";
                    goto PROC_EXIT;
                }

                #endregion

                #region 查询用户数据

                if (strUserId != "hcwy")
                {
                    List<xt_UserTable> listxt_UserTable = new SqlSugarRepository<xt_UserTable>(db).getByWhere(t => t.uCode == strUserId);
                    if (listxt_UserTable.Count == 0)
                    {
                        nret = 1;
                        strFanHuiZhi = "未查询到用户,请检查用户代码是否存在或有误！";
                        goto PROC_EXIT;
                    }
                    strUserName = listxt_UserTable[0].uName;
                    DataTable YuanQuQuanXian = new SqlSugarRepository<object>(db).getDataTableBySqlQuery($@"select YuanQuMingCheng from qx_YuanQu A with(nolock),jcsj_YuanQu B with(nolock) 
where A.YuanQuId = B.YuanQuID and uCode = '{strUserId}'");
                    if (YuanQuQuanXian.Rows.Count == 0)
                    {
                        nret = 1;
                        strFanHuiZhi = "此用户为未维护院区权限，请联系管理员！";
                        goto PROC_EXIT;
                    }
                    list院区 = YuanQuQuanXian.AsEnumerable().Select(t => t.Field<string>("YuanQuMingCheng")).ToList();
                }
                else
                {
                    strUserName = "管理员";
                    List<jcsj_YuanQu> listjcsj_YuanQu = new SqlSugarRepository<jcsj_YuanQu>(db).getAll();
                    if (listjcsj_YuanQu.Count == 0)
                    {
                        nret = 1;
                        strFanHuiZhi = "院区表未查询到记录，请联系管理员！";
                        goto PROC_EXIT;
                    }
                    foreach (jcsj_YuanQu jcsj_YuanQu in listjcsj_YuanQu)
                    {
                        list院区.Add(jcsj_YuanQu.YuanQuMingCheng);
                    }
                }

            #endregion

            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = new
                    {
                        UserName = strUserName,
                        YuanQu = list院区
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="strFanHuiZhi"></param>
        /// <param name="strJueSeId"></param>
        /// <param name="strUserId"></param>
        /// <param name="strRefresh_Token"></param>
        /// <param name="login"></param>
        /// <param name="stripaddress"></param>
        /// <param name="strDengLuXiTong"></param>
        /// <returns></returns>
        public int Login(out string strFanHuiZhi, out string strJueSeId, out string strUserId, out string strRefresh_Token, out string strYuanQuQianZhui, LoginClass login,string stripaddress,string strDengLuXiTong)
        {
            int nret = 0; strFanHuiZhi = ""; strJueSeId = ""; strUserId = ""; strRefresh_Token = ""; strYuanQuQianZhui = "";
            try
            {

                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:接收参数【{login}】");

                #region 声明变量

                string strUcode = "";
                string strUname = "";
                int iCuoWuCiShu = 0;
                string strShiFouSuoDing = "否";

                #endregion

                #region 验证数据

                if (string.IsNullOrEmpty(login.strDengLuXiTong))
                {
                    nret = 1;
                    strFanHuiZhi = "登录系统为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(login.strUserId))
                {
                    nret = 1;
                    strFanHuiZhi = "用户ID为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(login.strUserName))
                {
                    nret = 1;
                    strFanHuiZhi = "用户名为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(login.strYuanQu))
                {
                    nret = 1;
                    strFanHuiZhi = "院区为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(login.strPassWord))
                {
                    nret = 1;
                    strFanHuiZhi = "密码为空！";
                    goto PROC_EXIT;
                }

                #endregion

                #region 执行查询用户

                if (login.strUserId == "hcwy")
                {
                    if (login.strPassWord != "jnhcwy")
                    {
                        strFanHuiZhi = "用户名或密码有误！";
                        nret = 1;
                        goto PROC_EXIT;
                    }
                    strJueSeId = "0";
                    strUserId = login.strUserId;
                }
                else
                {
                    List<xt_UserTable> listxt_UserTable = new SqlSugarRepository<xt_UserTable>(db).getByWhere(t => t.uCode == login.strUserId);
                    if (listxt_UserTable.Count() == 0)
                    {
                        strFanHuiZhi = "用户名有误！";
                        nret = 1;
                        goto PROC_EXIT;
                    }
                    iCuoWuCiShu = int.Parse(string.IsNullOrEmpty(listxt_UserTable[0].CuoWuCiShu.ToString()) ? "0" : listxt_UserTable[0].CuoWuCiShu.ToString());
                    strShiFouSuoDing = string.IsNullOrEmpty(listxt_UserTable[0].ShiFouSuoDing)?"否": listxt_UserTable[0].ShiFouSuoDing;
                    if (strShiFouSuoDing == "是")
                    {
                        strFanHuiZhi = "当前用户已被锁定！";
                        nret = 1;
                        goto PROC_EXIT;
                    }
                    if (listxt_UserTable[0].uPWD != new MethodHelper(db).MD5Encrypt(login.strPassWord))
                    {
                        iCuoWuCiShu++;
                        if (iCuoWuCiShu >= 5)
                        {
                            strShiFouSuoDing = "是";
                            strFanHuiZhi = "当前用户密码错误次数过多，已被锁定！请联系管理员解锁";
                            nret = 1;
                            goto PROC_EXIT;
                        }
                        strFanHuiZhi = "密码错误！";
                        nret = 1;
                        goto PROC_EXIT;
                    }
                    iCuoWuCiShu = 0;
                    strShiFouSuoDing = "否";
                    strJueSeId = listxt_UserTable[0].JueSeID;
                    strUcode = listxt_UserTable[0].uCode;
                    strUserId = listxt_UserTable[0].uCode;
                    strUname = listxt_UserTable[0].uName;
                }

                #endregion

                #region 查询院区前缀

                strYuanQuQianZhui = new SqlSugarRepository<jcsj_YuanQu>(db).getByWhere(t => t.YuanQuMingCheng == login.strYuanQu).Select(t => t.TiJianHaoQianZhui).FirstOrDefault();

                #endregion

                #region 生成RefSalt

                if (new SqlSugarRepository<RefreshToken>(db).DeleteWhere(t => t.UserId == strUcode && t.ipaddress == stripaddress) == false)
                {
                    strFanHuiZhi = "数据库操作失败!";
                    nret = 1000;
                    goto PROC_EXIT;
                }
                //生成随机的RefSalt
                string strRefSalt = new MethodHelper(db).GetPasswordSalt();
                //存放数据库 拼接加密后的最终值
                string strJiaoYanKey = strRefSalt + strUserId + stripaddress;
                strJiaoYanKey = new MethodHelper(db).GetMD5Hash(strJiaoYanKey);
                //记录数据库加密信息
                RefreshToken Refresh = new RefreshToken();
                Refresh.ipaddress = stripaddress;
                Refresh.DengLuXiTong = strDengLuXiTong;
                Refresh.JueSeId = strJueSeId;
                Refresh.UserId = strUserId;
                Refresh.UserName = strUname;
                Refresh.YuanQuQianZhui = strYuanQuQianZhui;
                Refresh.YuanQu = login.strYuanQu;
                Refresh.RefSalt = strJiaoYanKey;
                Refresh.CreateTime = DateTime.Now;
                //执行插入数据库
                if (new SqlSugarRepository<RefreshToken>(db).Add(Refresh) == false)
                {
                    strFanHuiZhi = "数据库操作失败!";
                    nret = 1000;
                    goto PROC_EXIT;
                }

                //加密符串
                strRefresh_Token = new MethodHelper(db).MD5Encrypt(strRefSalt);
                //加密UserId 
                if (string.IsNullOrEmpty(strUserId) == false)
                {
                    strUserId = new MethodHelper(db).MD5Encrypt(strUserId);
                }

            #endregion


            PROC_EXIT:
                //修改数据库
                if (new SqlSugarRepository<xt_UserTable>(db).Update(t => new xt_UserTable
                {
                    CuoWuCiShu = iCuoWuCiShu,
                    ShiFouSuoDing = strShiFouSuoDing
                }, t => t.uCode == login.strUserId) == false)
                {
                    strRefresh_Token = "";
                    strFanHuiZhi = "数据库操作失败!";
                    nret = 1000;
                }
                return nret;
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                strFanHuiZhi = ex.Message;
                return 1000;
            }
        }
        /// <summary>
        /// 颁发refresh_token
        /// </summary>
        /// <param name="strFanHuiZhi"></param>
        /// <param name="strDengLuXiTong"></param>
        /// <param name="strJueSeId"></param>
        /// <param name="strUserName"></param>
        /// <param name="strYuanQuQianZhui"></param>
        /// <param name="strRefresh_Token"></param>
        /// <param name="strUserId"></param>
        /// <param name="strRefSalt"></param>
        /// <param name="stripaddress"></param>
        /// <returns></returns>
        public int RefreshToken(out string strFanHuiZhi,out string strDengLuXiTong,out string strJueSeId, out string strUserName,out string strYuanQuQianZhui, out string strYuanQu, out string strRefresh_Token, string strUserId, string strRefSalt,string stripaddress)
        {
            int nret = 0; strFanHuiZhi = ""; strDengLuXiTong = ""; strJueSeId = ""; strUserName = ""; strYuanQuQianZhui = ""; strYuanQu = ""; strRefresh_Token = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:接收参数【{strUserId}、{strRefSalt}】");

                #region 声明变量

                string JiaoYanKey = "";
                string strJiaoYanKey = "";

                #endregion

                #region 数据验证

                if (string.IsNullOrEmpty(strUserId))
                {
                    nret = 1;
                    strFanHuiZhi = "用户ID为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(strRefSalt))
                {
                    nret = 1;
                    strFanHuiZhi = "strRefSalt为空！";
                    goto PROC_EXIT;
                }
                nret = new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, strUserId);
                if (nret != 0)
                {
                    nret = 1;
                    strFanHuiZhi = "加密值校验未通过!";
                    goto PROC_EXIT;
                }
                strUserId = strFanHuiZhi;
                nret = new MethodHelper(db).MD5Decrypt(out strFanHuiZhi, strRefSalt);
                if (nret != 0)
                {
                    nret = 1;
                    strFanHuiZhi = "加密值校验未通过!";
                    goto PROC_EXIT;
                }
                strRefSalt = strFanHuiZhi;

                #endregion

                #region 开始比对

                JiaoYanKey = strRefSalt + strUserId + stripaddress;
                JiaoYanKey = new MethodHelper(db).GetMD5Hash(JiaoYanKey);
                List<RefreshToken> listRefreshToken = new SqlSugarRepository<RefreshToken>(db).getByWhere(t => t.UserId == strUserId && t.ipaddress == stripaddress);
                if (listRefreshToken.Count() == 0)
                {
                    nret = 1;
                    strFanHuiZhi = "错误,未找到校验信息";
                    goto PROC_EXIT;
                }
               
                //校验时间和当前时间相差多久
                DateTime DangQianTime = DateTime.Now;
                DateTime KeyCreateTime = (DateTime)listRefreshToken[0].CreateTime;
                TimeSpan duration = DangQianTime - KeyCreateTime;
                int minutesDifference = (int)duration.TotalMinutes;
                strDengLuXiTong = listRefreshToken[0].DengLuXiTong;
                strJueSeId = listRefreshToken[0].JueSeId;
                strYuanQuQianZhui = listRefreshToken[0].YuanQuQianZhui;
                strYuanQu = listRefreshToken[0].YuanQu;

                if (minutesDifference >= 300)
                {
                    nret = 2;
                    strFanHuiZhi = "当前,Refresh_Token已失效!";
                    goto PROC_EXIT;
                }
                if (JiaoYanKey != listRefreshToken[0].RefSalt)
                {
                    nret = 1;
                    strFanHuiZhi = "错误,校验信息未通过";
                    goto PROC_EXIT;
                }

                #endregion

                #region 查询用户信息

                List<xt_UserTable> listxt_UserTable = new SqlSugarRepository<xt_UserTable>(db).getByWhere(t => t.uCode == strUserId);
                if (listxt_UserTable.Count() == 0)
                {
                    nret = 1;
                    strFanHuiZhi = "错误,未找到用户信息";
                    goto PROC_EXIT;
                }
                strUserName = listxt_UserTable[0].uName;

                #endregion

                #region 生成新的RefSalt

                if (new SqlSugarRepository<RefreshToken>(db).DeleteWhere(t => t.UserId == strUserId) == false)
                {
                    nret = 1000;
                    strFanHuiZhi = "数据库操作失败!";
                    goto PROC_EXIT;
                }
                //生成随机的RefSalt
                strRefSalt = new MethodHelper(db).GetPasswordSalt();
                //存放数据库 拼接加密后的最终值
                strJiaoYanKey = strRefSalt + strUserId + stripaddress;
                strJiaoYanKey = new MethodHelper(db).GetMD5Hash(strJiaoYanKey);
                //记录数据库加密信息
                RefreshToken Refresh = new RefreshToken();
                Refresh.ipaddress = stripaddress;
                Refresh.DengLuXiTong = strDengLuXiTong;
                Refresh.JueSeId = strJueSeId;
                Refresh.UserId = strUserId;
                Refresh.UserName = strUserName;
                Refresh.YuanQuQianZhui = strYuanQuQianZhui;
                Refresh.YuanQu = strYuanQu;
                Refresh.RefSalt = strJiaoYanKey;
                Refresh.CreateTime = DateTime.Now;
                //执行插入数据库
                if (new SqlSugarRepository<RefreshToken>(db).Add(Refresh) == false)
                {
                    nret = 1000;
                    strFanHuiZhi = "数据库操作失败!";
                    goto PROC_EXIT;
                }
                //加密符串
                strRefresh_Token = new MethodHelper(db).MD5Encrypt(strRefSalt);


            #endregion


            PROC_EXIT:
                return nret;
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                strFanHuiZhi = ex.Message;
                return 1000;
            }
        }

    }
}
